package org.gpslw.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.geolatte.geom.ByteBuffer;
import org.geolatte.geom.codec.Wkb;
import org.geolatte.geom.jts.JTS;
import org.locationtech.jts.geom.Geometry;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Geometry.class)
public class GeometryTypeHandler extends BaseTypeHandler<Geometry> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        String wkb = Wkb.toWkb(JTS.from(parameter)).toString();
        ps.setString(i, wkb);
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String wkb = rs.getString(columnName);
        return JTS.to(Wkb.fromWkb(ByteBuffer.from(wkb)));
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String wkb = rs.getString(columnIndex);
        return JTS.to(Wkb.fromWkb(ByteBuffer.from(wkb)));
    }

    @Override
    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String wkb = cs.getString(columnIndex);
        return JTS.to(Wkb.fromWkb(ByteBuffer.from(wkb)));
    }
}
